#include <webx/route.h>
#include <dbentity/T_XG_FILE.h>

#ifdef MoveFile
#undef MoveFile
#endif

class MoveFile : public webx::ProcessBase
{
protected:
	int process();
};

HTTP_WEBAPP(MoveFile)

#ifdef MoveFile
#undef MoveFile
#endif

int MoveFile::process()
{
	param_string(src);
	param_string(dest);
	param_string(flag);
	param_string(remark);

	webx::CheckFilePath(src, 1);
	webx::CheckFilePath(dest, 0);
	
	const string& user = checkLogin();

	checkSystemRight();

	src = app->getPath() + src;
	src = stdx::replace(src, "\\", "/");
	src = stdx::replace(src, "//", "/");

	dest = app->getPath() + dest;
	dest = stdx::replace(dest, "\\", "/");
	dest = stdx::replace(dest, "//", "/");

	if (flag == "C")
	{
		if (!path::mkdir(src)) return simpleResponse(XG_SYSERR);

		dest = src;
	}

	auto getId = [&](const string& dest){
		return dest.substr(app->getPath().length() - 1);
	};

	int res = 0;
	string sqlcmd;
	CT_XG_FILE tab;
	sp<DBConnect> dbconn = webx::GetDBConnect();

	if (flag == "D")
	{
		tab.init(dbconn);
		tab.id = getId(src);

		if ((res = tab.remove()) < 0) return simpleResponse(res);
	
		stdx::format(sqlcmd, "ID LIKE '%s/%%'", getId(src).c_str());

		if ((res = tab.remove(sqlcmd)) < 0) return simpleResponse(res);

		path::remove(src);		
	}
	else
	{
		string id = getId(dest);

		if (id.empty()) return simpleResponse(XG_PARAMERR);

		if (path::type(src) <= eNONE) return simpleResponse(XG_PARAMERR);

		tab.init(dbconn);

		if (src == dest)
		{
			src.clear();
		}
		else
		{
			if (flag == "U")
			{
				tab.id = id;

				if ((res = tab.remove()) < 0) return simpleResponse(res);
				
				vector<string> vec;
				string sid = getId(src);

				stdx::format(sqlcmd, "ID LIKE '%s/%%'", sid.c_str());

				if (!tab.find(sqlcmd)) return simpleResponse(XG_SYSERR);
				
				while (tab.next()) vec.push_back(tab.id.val());

				for (auto& item : vec)
				{
					string tmp = id + item.substr(sid.length());

					stdx::format(sqlcmd, "UPDATE T_XG_FILE SET ID='%s' WHERE ID='%s'", tmp.c_str(), item.c_str());

					if ((res = dbconn->execute(sqlcmd)) < 0) return simpleResponse(res);
				}
	
				path::remove(dest);
			}
			else
			{
				if (path::type(dest) > eNONE) return simpleResponse(XG_DUPLICATE);
			}

			path::rename(src, dest);
		}

		tab.id = id;
		tab.rid = user;
		tab.imme = "FILE";
		tab.type = "FILE";
		tab.remark = remark;
		tab.content = "FILE";
		tab.statetime.update();
	
		if (remark.empty())
		{
			res = tab.remove();
		}
		else
		{
			if ((res = tab.insert()) < 0) res = tab.update();
		}

		json["url"] = getId(dest);
	}

	json["code"] = res;
	out << json;

	return XG_OK;
}